<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\model;

use think\Model;
use app\admin\model\Config as ConfigModel;
use think\Db;
use app\mill\model\Give as GiveModel;

/**
 * 面积表模型
 */
class Archives extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'mill_order_archives';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 定义表格字段
    public static $fields_old = [
        'sort'          =>  '序号',
        'page'          =>  '图号',
        'model_sn'      =>  '编号',
        'thickness'     =>  '板厚(MM)',
        'long'          =>  '长(L)',
        'high'          =>  '宽(W)',
        'one_area'      =>  '单件面积(M²)',
        'number'        =>  '数量',
        //'cutting'       =>  '开料',
        //'size'          =>  '尺寸',
        'row_area'      =>  '合计面积(M²)',
        'color'         =>  '颜色',
        //'plank'         =>  '板材',
        'model'         =>  '板型',
    ];
    // 定义表格字段
    public static $fields = [
        'sort'          =>  '序号',
        'model_sn'      =>  '编号',
        'page'          =>  '页码',
        'number'        =>  '数量',
        'long'          =>  '长(L)',
        'high'          =>  '宽(W)',
        //'cutting'       =>  '折弯',
        //'size'          =>  '尺寸',
        'one_area'      =>  '单件面积(M²)',
        'row_area'      =>  '合计面积(M²)',
        'color'         =>  '颜色',
        'thickness'     =>  '板厚(MM)',
        'plank'         =>  '板材',
        'model'         =>  '板型',
    ];

    // 定义已发货表格字段
    public static $fields4 = [
        'sort'          =>  '序号',
        'archives_sn'   =>  '档案号',
        'page'          =>  '图号',
        'model_sn'      =>  '编号',
        'thickness'     =>  '板厚',
        'long'          =>  '长',
        'high'          =>  '宽',
        'one_area'      =>  '单件面积(M²)',
        'number'        =>  '数量',
        'row_area'      =>  '合计面积(M²)',
        'color'         =>  '颜色',
        'model'         =>  '版型',
        'slot'          =>  '开槽',
        'weld'          =>  '焊缝',
        'torque'        =>  '超宽(M)',
        'bend'          =>  '超长(M)',
    ];

    /**
     * 获取面积表信息
     * @param null $id order_id
     * @param string $fields field
     * @param string $order order
     * @param string $group group
     * @param array $join join
     * @param array $where where
     * @param string $table table
     * @return array|\PDOStatement|string|\think\Collection
     */
    public static function getList($id = null,$fields = '',$order = "CONVERT (REPLACE(a.sort,'#','999999'),signed) ASC",$group = '',$join = [],$where = [],$table = 'mill_order_archives'){
        if (!$id && empty($where))return [];
        if(empty($order))$order = "CONVERT (REPLACE(a.sort,'#','999999'),signed) ASC";

        if(empty($where))$where[] = ['a.order_id','=',$id];
        $fields = $fields?$fields:array_keys(self::$fields);

        $lists = Db::name($table)->alias('a')->field($fields)->join($join)->where($where)->group($group)->orderRaw($order)->select();

        return $lists;

    }

    // 统计工程面积表信息
    public static function getOneStat($val = null,$field = 'order_id',$condition = 'eq',$map = [],$time = [],$status = 0){
        $where[] = ['a.'.$field,$condition,$val];
        $where_give = [['g.quality_status','>=',0]];
        if(!empty($map))$where = $map;
        if(empty($time[0]))$time[0] = 0;
        if(empty($time[1]))$time[1] = time();
        $data['number_sum'] = Db::name('mill_order_archives')->alias('a')->where($where)->sum('number');
        if(!empty($status)){
            $data["status_sum"] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status{$status}_time > {$time[0]} and g.status{$status}_time <= {$time[1]}")->count();
            $data["status_no"] = $data['number_sum']-$data["status_sum"];
        }
        else{
            $data['status1'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status1_time > {$time[0]} and g.status1_time <= {$time[1]}")->count();
            $data['status1_no'] = $data['number_sum']-$data['status1'];
            $data['status2'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status2_time > {$time[0]} and g.status2_time <= {$time[1]}")->count();
            $data['status2_no'] = $data['number_sum']-$data['status2'];
            $data['status3'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status3_time > {$time[0]} and g.status3_time <= {$time[1]}")->count();
            $data['status3_no'] = $data['number_sum']-$data['status3'];
            $data['status4'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status4_time > {$time[0]} and g.status4_time <= {$time[1]}")->count();
            $data['status4_no'] = $data['number_sum']-$data['status4'];
            $data['status5'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status5_time > {$time[0]} and g.status5_time <= {$time[1]}")->count();
            $data['status5_no'] = $data['number_sum']-$data['status5'];
        }

        $status_s = !empty($status)?$status:4;
        $data['area_sum'] = Db::name('mill_order_archives')->alias('a')->where($where)->sum('one_area*number');
        $data['area_sum'] = round($data['area_sum'],4);
        $data['area_ok_sum'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status>={$status_s}")->sum('a.one_area');
        $data['area_ok_sum'] = round($data['area_ok_sum'],4);
        $data['area_on_sum'] = $data['area_sum']-$data['area_ok_sum'];

        $data['number_ok_sum'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status>={$status_s}")->count();
        $data['number_ok_sum'] = intval($data['number_ok_sum']);
        $data['number_on_sum'] = $data['number_sum']-$data['number_ok_sum'];

        if(!empty($status)){
            $data["status_area_sum"] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status{$status}_time > {$time[0]} and g.status{$status}_time <= {$time[1]}")->sum('a.one_area');
            $data["status_area_sum"] = round($data["status_area_sum"],6);
            $data["status_area_on_sum"] = $data['area_sum']-$data["status_area_sum"];
        }
        else{
            //已开料面积
            $data['status1_area_sum'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status1_time > {$time[0]} and g.status1_time <= {$time[1]}")->sum('a.one_area');
            $data['status1_area_sum'] = round($data['status1_area_sum'],4);
            $data['status1_area_on_sum'] = $data['area_sum']-$data['status1_area_sum'];
            //已钣金面积
            $data['status2_area_sum'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status2_time > {$time[0]} and g.status2_time <= {$time[1]}")->sum('a.one_area');
            $data['status2_area_sum'] = round($data['status2_area_sum'],4);
            //未钣金面积
            $data['status2_area_on_sum'] = $data['area_sum']-$data['status2_area_sum'];
            //已喷涂面积
            $data['status3_area_sum'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status3_time > {$time[0]} and g.status3_time <= {$time[1]}")->sum('a.one_area');
            $data['status3_area_sum'] = round($data['status3_area_sum'],4);
            //未喷涂面积
            $data['status3_area_on_sum'] = $data['area_sum']-$data['status3_area_sum'];
            //已复合面积
            $data['status4_area_sum'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status4_time > {$time[0]} and g.status4_time <= {$time[1]}")->sum('a.one_area');
            $data['status4_area_sum'] = round($data['status4_area_sum'],4);
            //未复合面积
            $data['status4_area_on_sum'] = $data['area_sum']-$data['status4_area_sum'];
            //已发货面积
            $data['status5_area_sum'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where($where)->where($where_give)->where("g.status5_time > {$time[0]} and g.status5_time <= {$time[1]}")->sum('a.one_area');
            $data['status5_area_sum'] = round($data['status5_area_sum'],4);
            //未发货面积
            $data['status5_area_on_sum'] = $data['area_sum']-$data['status5_area_sum'];
        }

        return $data;
    }

    // 插入产品明细
    public static function checkGive($id=null,$archives_id=null){
        $config = new ConfigModel();

        $where = $where2 = ['order_id'=>$id];
        if(!empty($archives_id)){
            $where = ['archives_id'=>$archives_id];
            $where2 = ['id'=>$archives_id];
        }
        $count = Db::name('mill_order_archives_give')->where($where)->count();

        if(empty($count)){

            if(empty($archives_id)){
                //当天生产批次配置
                $mill_date_batch = $config->getConfig('mill_date_batch');
                //如果不是当天生产批次，则重置
                if($mill_date_batch['date']!=date('Ymd')){
                    $mill_date_batch['date'] = date('Ymd');
                    $mill_date_batch['batch'] = 0;
                }
                $mill_date_batch['batch'] += 1;
                $mill_date_batch['sort'] = 1;
            }
            else{
                $last_give = Db::name('mill_order_archives_give')->where(['order_id'=>$id])->order('sort desc')->find();
                $mill_date_batch['date'] = $last_give['give_date'];
                $mill_date_batch['batch'] = $last_give['batch'];
                $mill_date_batch['sort'] = $last_give['sort']+1;
            }

            //当天日期
            $date = $mill_date_batch['date'];
            //当前批次
            $batch = $mill_date_batch['batch'];
            //当前序号，从1开始
            $sort = $mill_date_batch['sort'];

            $order = Db::name('mill_order')->where('id='.$id)->find();
            $list = self::getList(null,'id,order_id,order_pid,sort,number,sort','','',[],$where2,'mill_order_archives');
            $add_arr = [];
            foreach ($list as $v){

                if($v['number'] >= 1){
                    for ($i=1;$i<=$v['number'];$i++){
                        $add = [
                            'order_id'      =>  $v['order_id'],
                            'order_pid'     =>  $v['order_pid'],
                            'archives_id'   =>  $v['id'],
                            'archives_sn'   =>  $order['archives_sn'],
                            'number'        =>  1,
                            'counter'       =>  $i,
                            'give_date'     =>  $date,
                            'batch'         =>  $batch,
                            'sort'          =>  $sort,
                            'give_sn'       =>  GiveModel::giveSn($date,$batch,$sort),
                        ];
                        $add_arr[] = $add;

                        $sort++;
                    }
                }
            }

            //2000条数据为一批次
            $add_arr_i = intval($sort/2000)+1;
            $add_arr_arr = array_chunk($add_arr, $add_arr_i);
            //分批次插入
            foreach ($add_arr_arr as $varr){
                Db::name('mill_order_archives_give')->insertAll($varr);
            }

            //更新当天生产批次配置
            if(empty($archives_id))ConfigModel::where('name', 'mill_date_batch')->update(['value' => "date:{$date}\r\nbatch:{$batch}"]);
        }

        return true;
    }

    // 检查更新产品状态
    public static function checkStatus($id=null,$status=0){
        if($status>0){
            $where = ['id'=>$id];
            $data = Db::name('mill_order_archives')->field('order_id,number')->where($where)->find();
            $count = Db::name('mill_order_archives_give')->where(['archives_id'=>$id])->where('status>='.$status)->count('id');
            if($count >= $data['number']){

                $update = ['status'=>$status+1];
                Db::name('mill_order_archives')->where($where)->update($update);

                //更新工程生产周期
                if($status == 3){
                    $give_pro_min = Db::name('mill_order_archives_give')->where(['order_id'=>$data['order_id']])->order('status1_time asc')->value('status1_time');
                    $give_pro_max = Db::name('mill_order_archives_give')->where(['order_id'=>$data['order_id']])->order('status3_time desc')->value('status3_time');
                    $give_pro = ceil(($give_pro_max/86400)-($give_pro_min/86400));
                    Db::name('mill_order')->where(['id'=>$data['order_id']])->update(['give_pro'=>$give_pro]);
                }

            }

            //更新工程产品状态
            $give_status = Db::name('mill_order_archives_give')->where(['order_id'=>$data['order_id']])->order('status desc')->value('status');

            Db::name('mill_order')->where(['id'=>$data['order_id']])->update(['give_status'=>$give_status]);
        }
    }
}
